<template>
  <div class="content-item pageView">
    <h1 class="left-tit-more">
      <a  class="tit">
        <span>留言数量/回复数量</span>
      </a>
      <div class="total-num">
        <div class="num">留言：<span>{{totalComment}}</span></div>
        <div class="num">回复：<span>{{totalReply}}</span></div>
      </div>
      <!-- <router-link to="/statistics/visit/page" class="more">更多></router-link> -->
    </h1>
    <div class="top-tool">
      <div class="total">
        <div class="pv total-item">
          <span>留言数量</span>
          <p class="pv"></p>
        </div>
        <div class="uv total-item">
          <span>回复数量</span>
          <p></p>
        </div>
      </div>
      <div class="right-box">
        <div class="btn-box">
          <div v-for="(item, index) in dateTypeList" class="btn" :class="{ active: currentIndex == index }" :key="index" @click="changeDateType(index, item.value)">{{ item.label }}</div>
        </div>
        <!-- <el-date-picker v-model="dateRange" type="monthrange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" class="date-picker" /> -->
      </div>
    </div>
    <div ref="main" style="height: 350px; width: 100%" v-loading="tableLoading"></div>
  </div>
</template>
<script setup>
import { getCommentAndReplyCount } from "@/api/count";
import { onMounted, ref, reactive, watch } from 'vue'
import dayjs from 'dayjs'
import echarts from '@/utils/echarts'

const main = ref(null) //获取dom
const dateRange = ref('')

const dateTypeList = ref([
  { value: 0, label: '今日' },
  { value: 1, label: '昨日' },
  { value: 2, label: '近7日' },
  { value: 3, label: '近30日' }
])
const currentIndex = ref(0)
//改变时间
const changeDateType = (index, dateType) => {
  currentIndex.value = index
  const now = dayjs()
  let startTime, endTime, xAxisType
  switch (dateType) {
    case 0: // 今日
      startTime = now.startOf('day')
      endTime = now
      xAxisType = 0
      break
    case 1: // 昨日
      startTime = now.subtract(1, 'day').startOf('day')
      endTime = now.subtract(1, 'day').endOf('day')
      xAxisType = 0
      break
    case 2: // 近7日
      startTime = now.subtract(6, 'day').startOf('day')
      endTime = now
      xAxisType = 1
      break
    case 3: // 近30日
      startTime = now.subtract(29, 'day').startOf('day')
      endTime = now
      xAxisType = 1
      break
  }

  params.list = getTimeSegments(startTime, endTime, xAxisType)
  getPageView(params)
}

watch(dateRange, newVal => {
  console.log("dateRange",dateRange);
  if (dateRange.value && dateRange.value[0]) {
    const timeSegments = getTimeSegments(dateRange.value[0], dateRange.value[1], newVal)
    params.list = timeSegments
    console.log("params.list",params.list);
    getPageView(params)
  }
})
const getTimeSegments = (startDate, endDate, xAxisType) => {
  const result = []

  if (xAxisType === 0) {
    // 按时
    const now = new Date()
    const actualEndDate = endDate.valueOf() > now.valueOf() ? now : endDate
    const totalTime = actualEndDate.valueOf() - startDate.valueOf()
    const segmentDuration = Math.floor(totalTime / 8)

    for (let i = 0; i < 8; i++) {
      const segmentStart = startDate.valueOf() + segmentDuration * i
      const segmentEnd = i === 5 ? actualEndDate.valueOf() : startDate.valueOf() + segmentDuration * (i + 1)

      result.push({
        startTime: segmentStart,
        endTime: segmentEnd,
        key: `${dayjs(segmentStart).format('HH:mm')}-${dayjs(segmentEnd).format('HH:mm')}`
      })
    }
  } else {
    // 计算总时间跨度并确定分段数
    const totalDays = dayjs(endDate).diff(startDate, 'day')
    let segments = 8

    // 根据时间跨度调整分段数
    if (totalDays < 9) segments = totalDays

    const daysPerSegment = Math.ceil(totalDays / segments)

    for (let i = 0; i < segments; i++) {
      const segmentStart = dayjs(startDate).add(daysPerSegment * i, 'day')
      const segmentEnd = i === segments - 1 ? dayjs(endDate) : dayjs(startDate).add(daysPerSegment * (i + 1), 'day')

      let format
      switch (xAxisType) {
        case 1: // 按日
          format = 'MM-DD'
          break
        case 2: // 按周
          format = 'MM-DD'
          break
        case 3: // 按月
          format = 'YYYY-MM'
          break
        case 4: // 按年
          format = 'YYYY'
          break
        default:
          format = 'MM-DD'
      }

      result.push({
        startTime: segmentStart.valueOf(),
        endTime: segmentEnd.valueOf(),
        key: `${segmentStart.format(format)}-${segmentEnd.format(format)}`
      })
    }
  }

  return result
}
const params = reactive({
  list: []
})
const data = reactive({
  allInfo: {}
})
const tableLoading = ref(false)
let myChart
const totalComment = ref()
const totalReply = ref()
const getPageView = async params => {
  tableLoading.value = true
  let res = await getCommentAndReplyCount(params)
  if (res.code == 20000) {
    data.allInfo = res.data.list
    totalComment.value = res.data.totalComment
    totalReply.value = res.data.totalReply
    let time = res.data.list.map(item => item['key'])
    let comment_data = res.data.list.map(item => item['commentCount'])
    let reply_data = res.data.list.map(item => item['replyCount'])
    myChart.setOption({
      xAxis: {
        data: time
      },
      series: [
        {
          name: '留言数量',
          data: comment_data
        },
        {
          name: '回复数量',
          data: reply_data
        }
      ]
    })
  }
  tableLoading.value = false
}
onMounted(() => {
  myChart = echarts.init(main.value)
  myChart.setOption({
    title: {},
    tooltip: {},
    grid: {
      // 让图表占满容器
      top: '25',
      left: '68',
      right: '25',
      bottom: '25'
    },
    xAxis: {
      data: [],
      axisTick: {
        show: false
      },
      axisLine: {
        onZero: false
      },
      boundaryGap: false
    },
    yAxis: {
      axisLine: {
        show: true
      },
      splitArea: {
        show: true, //分割区域
        areaStyle: {
          color: ['#fff', '#F8F8F8']
        }
      }
    },
    width: '100%',
    series: [
      {
        name: '留言数量',
        type: 'line',
        data: [],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        color: '#FF9700'
      },
      {
        name: '回复数量',
        type: 'line',
        data: [],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        color: '#4D99F2'
      }
    ]
  })
  changeDateType(0, 0)

  window.onresize = function () {
    myChart.resize()
    if (process.env.NODE_ENV === 'development') console.log(11)
  }
})
</script>
<style lang="scss" scoped>
.pageView {
  position: relative;
  padding: 20px;
  background: #ffffff;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 0 10px rgba(#000, 0.1);
  .left-tit-more {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .tit {
      display: flex;
      align-items: center;
      font-size: 16px;
    }
    .more {
      font-size: 14px;
      color: #7f7f7f;
    }
    .total-num{
      display: flex;
      .num{
        padding: 5px 15px;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 18px;
        margin-left: 10px;
        color: $black_2;
        span{
          font-size: 20px;
          color: $mainColor;
        }
      }
    }
  }
  .top-tool {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    .total {
      display: flex;
      .total-item {
        display: flex;
        align-items: center;
        span {
          font-size: 14px;
          color: #333333;
        }
        p {
          margin-left: 10px;
          width: 40px;
          height: 2px;
        }
        &.pv p {
          background: #ff9700;
        }
        &.uv {
          margin-left: 40px;
          p {
            background: #4d99f2;
          }
        }
      }
    }
    .right-box{
      display: flex;
      align-items: center;
      /* .btn-box{ 
        margin-right: 20px;
       } */
    }
    .btn-box {
      display: flex;
      border-radius: 4px;
      overflow: hidden;
      .btn {
        padding: 0 17px;
        font-size: 14px;
        line-height: 30px;
        background-color: rgba(#000, 0.04);
        color: #7f7f7f;
        border: 1px solid #dcdfe6;
        cursor: pointer;
        & + .btn {
          border-left: none;
        }
        &.active {
          border: none;
          background-color: $mainColor;
          color: #fff;
        }
      }
    }
  }
}
</style>
